<?php
declare (strict_types=1);

namespace addons\V2\admin\model;

use app\common\model\Base;

class ProductSpecData extends Base
{

    protected $name = 'addons_mall_product_spec_data';

    public static function setSpecData($pid, $data, $business = '')
    {
        try {
            parent::destroy(['pid' => $pid]);

            $all = [];
            foreach ($data as $v) {
                $key['pid'] = $pid;
                $key['spec_id'] = $v['id'];
                $key['spec_name'] = $v['title'];
                $key['child'] = [];
                foreach ($v['child'] as $item) {
                    if ($business) {
                        $item['checked'] = $item['checked'] == '1' || $item['checked'] == 'true' ? 'true' : 'false';
                    }
                    if ($item['checked'] == 'true') {
                        $key['child'][] = $item;
                    }
                }
                $key['child'] = json_encode($key['child']);
                $all[] = $key;
            }
            (new self())->insertAll($all);

            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    public static function getSpecData($pid, $api = false)
    {
        try {

            $list = parent::where('pid', $pid)->select();

            foreach ($list as $key => $v) {
                $v['child'] = json_decode($v['child'], true);
                if ($api) {
                    if (empty($v['child'])) {
                        unset($list[$key]);
                    }
                }
            }
            return array_values($list->toArray());

        } catch (\Exception $e) {
            return [];
        }
    }
}
